<template>
  <div class="edit-account-dialog-container" v-if="visible">
    <ChooseOrg
      :modal="false"
      :dialogVisible.sync="chooseOrgDialogVisible"
      :orgType="chooseOrgType"
      :title="title"
      @callback="chooseOrgCb"
    ></ChooseOrg>
    <!-- 选择岗位弹框 -->
    <!-- <el-dialog title="选择岗位"
               :visible.sync="organizationDialogVisible"
               width="40%">
      <el-row>
        <el-col :span='12'>
          <OrganizationTree :curMenu.sync="selectedNode"
                            :selectProject='true'></OrganizationTree>
        </el-col>
      </el-row>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="organizationDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="selectDept">确 定</el-button>
      </span>
    </el-dialog>-->
    <el-dialog
      :visible.sync="visible"
      width="60%"
      @close="dialogClose"
      :close-on-click-modal="false"
      :title="dialogStatus==='edit'?'编辑账号':'新增账号'"
    >
      <el-form
        :model="editAccountData"
        class="edit-account-form"
        status-icon
        ref="editAccountData"
        :rules="rules"
        label-width="100px"
      >
        <!-- <el-row>
          <el-col :span="11">
            <el-form-item label="单位类型"
                          prop="company_type">
              <el-select v-model="editAccountData.company_type">
                <el-option label="选择单位类型"
                           value="0">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11"
                  :offset="1">
            <el-form-item label="所属公司"
                          prop="account_company">
              <el-select v-model="editAccountData.account_company">
                <el-option label="选择所属公司"
                           value="0">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>-->
        <el-row class="phone-row">
          <el-col :span="11">
            <el-form-item label="手机号" prop="phone">
              <el-input
                class="phone"
                v-model="editAccountData.phone"
                maxlength="11"
                placeholder="请输入手机号"
              ></el-input>
              <el-button @click="checkPhone" :disabled="dialogStatus==='edit'" type="primary">检查</el-button>
            </el-form-item>
            <p
              :class="{'alert':checkPhoneRes.type===1,'normal':checkPhoneRes.type===2}"
              class="check-phone-res"
            >{{checkPhoneRes.msg}}</p>
          </el-col>
          <el-col :span="11" :offset="1">
            <!-- <el-form-item label="权限模板"
                          prop="permission_template">
              <el-select v-model="editAccountData.permission_template">
                <el-option label="选择权限模板"
                           value="0">
                </el-option>
              </el-select>
            </el-form-item>-->
            <el-form-item label="用户名" prop="user_name">
              <el-input v-model="editAccountData.user_name" placeholder="请输入用户名，英文和数字格式"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row>
          <el-col :span="11">
            <el-form-item label="用户昵称"
                          prop="user_nickname">
              <el-input v-model="editAccountData.user_nickname"
                        placeholder="请输入用户昵称">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11"
                  :offset="1">
            <el-form-item label="真实姓名"
                          prop="real_name">
              <el-input v-model="editAccountData.real_name"
                        placeholder="请输入真实姓名">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>-->
        <el-row>
          <el-col :span="11">
            <el-form-item label="岗位" prop="job_id">
              <el-select
                v-model="editAccountData.job_id"
                readonly
                @focus="openManageDialog"
                popper-class="select-class"
                placeholder="请选择岗位"
              >
                <el-option
                  v-for="item in jobList"
                  :key="item.job_id"
                  :label="item.job_name"
                  :value="item.job_id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11" :offset="1">
            <el-form-item label="真实姓名" prop="real_name">
              <el-input v-model="editAccountData.real_name" placeholder="请输入真实姓名"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="11">
            <el-form-item label="上传证书">
              <el-upload
                class="company-logo-upload"
                ref="uploadFile"
                :http-request="uploadFile"
                action
                :show-file-list="false"
                :limit="5-filesList.length"
                accept=".pdf, .doc, .docx, .jpg"
                :multiple="true"
                :disabled="filesList.length===5"
                :auto-upload="false"
                :file-list="fileList"
                :on-success="handleFileSuccess"
                :on-change="handleFileChange"
                :on-exceed="handleFileExceed"
                :before-upload="beforeFileUpload"
              >
                <!-- icon="el-icon-top" -->
                <el-button
                  class="upload"
                  size="small"
                  :disabled="filesList.length===5"
                  :type="filesList.length===5?'info':'primary'"
                >上传</el-button>
                <div slot="tip" class="el-upload__tip tip-height">只能上传PDF、WORD、JPG，且不超过50M,最多上传5个</div>
              </el-upload>

              <div class="accept-position">
                <ul>
                  <li v-for="(item, ind) in filesList">
                    <p :title="item.fileName">{{ item.fileName }}</p>
                    <p>
                      <el-button type="danger" size="mini" @click="deleteCurrentRow(item, ind)">删除</el-button>
                      <el-button type="primary" size="mini" @click="lookAndDown(item)">查看及下载</el-button>
                    </p>
                  </li>
                </ul>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- <el-row v-if="dialogStatus==='add'">
          <el-col :span="11">
            <el-form-item label="登录密码"
                          prop="login_password">
              <el-input v-model="editAccountData.login_password"
                        placeholder="请输入登录密码">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11"
                  :offset="1">
            <el-form-item label="重复密码"
                          prop="repeat_password">
              <el-input v-model="editAccountData.repeat_password"
                        placeholder="请输入重复密码">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          :disabled="checkPhoneRes.type!==2 && dialogStatus==='add'"
          type="primary"
          icon="el-icon-document"
          @click="saveData('editAccountData')"
        >保 存</el-button>
        <el-button @click="cancelData('editAccountData')">取 消</el-button>
        <p style="bottom:13%" class="tips">密码需包含大小写字母、数字及特殊字符，长度在10-32位之间</p>
        <p style="bottom:6%" class="tips">默认密码为（Aa@手机号）例如：Aa@188****1234</p>
      </div>
    </el-dialog>
    <el-dialog
      :title="'正在上传(' + uploadFileIndex + '/' + uploadQuene.length + ')'"
      width="768px"
      @close="uploadDialogClose"
      :visible.sync="uploadQueneDialogVisible"
    >
      <ul class="upload-quene-list">
        <li class="upload-quene-item" v-for="(item, index) in uploadQuene" :key="index">
          <span class="file-name">
            <img src="@/assets/file-icon.png" alt />
            <i>{{ item.name }}</i>
          </span>
          <span class="file-size">{{ item.file_size }}</span>
          <span v-if="item.status !== 'resolve'" class="staus">
            {{
            item.percent
            }}
          </span>
          <span class="status" v-if="item.status === 'resolve'">
            <i class="fa fa-check-circle"></i>
          </span>
        </li>
      </ul>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog" type="primary">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import OSS from "ali-oss";
import moment from "moment"; //时间处理库
import { accountApi } from "@/services/CompanySetting";
// import OrganizationTree from '@/components/OrganizationTree/OrganizationTree'
import ChooseOrg from "../../../../components/ChooseOrg/ChooseOrg";
import { ZHGDConsSitApi } from "@/services/ProjectCenter";
export default {
  components: {
    // OrganizationTree,
    ChooseOrg
  },
  data() {
    var checkUserName = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入用户名"));
      } else if (!/^[0-9a-zA-Z]{1,}$/.test(value)) {
        callback(new Error("请输入字母和数字的组合"));
      } else {
        callback();
      }
    };
    // var checkNickName = (rule, value, callback) => {
    //   if (value === '') {
    //     callback(new Error('请输入用户昵称'));
    //   } else {
    //     callback();
    //   }
    // };
    var checkRealName = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入真实姓名"));
      } else {
        callback();
      }
    };
    var checkJobId = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请选择岗位"));
      } else {
        callback();
      }
    };

    var checkPhone = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入手机号"));
      } else if (!/^[1][2,3,4,5,6,7,8,9][0-9]{9}$/.test(value)) {
        callback(new Error("请输入正确的手机号"));
      } else {
        callback();
      }
    };
    return {
      chooseOrgDialogVisible: false,
      chooseOrgType: "job", //company
      title: "选择岗位",
      selectedNode: {},
      // 上传文件进度弹框是否可见
      uploadQueneDialogVisible: false,
      fileList: [],
      filesList: [],
      // 等待上传文件列表
      uploadQuene: [],
      // 当前上传文件在列表中的index
      uploadFileIndex: 0,
      organizationDialogVisible: false,
      visible: false,
      editAccountData: {
        user_name: "",
        real_name: "",
        job_id: "",
        phone: "",
        job_cert: ""
      },
      rules: {
        user_name: [{ validator: checkUserName, trigger: "blur" }],
        real_name: [{ validator: checkRealName, trigger: "blur" }],
        job_id: [{ validator: checkJobId, trigger: "change" }],
        phone: [{ validator: checkPhone, trigger: "blur" }]
      },
      jobList: [],
      user_id: "",
      // edit_user_id: '',
      checkPhoneRes: {}
    };
  },
  props: {
    dialogVisible: Boolean,
    dialogStatus: {
      type: String,
      default: "create"
    },
    dialogId: String,
    dialogForm: Object
  },
  methods: {
    checkPhone() {
      this.$refs.editAccountData.validateField("phone", msg => {
        console.log(msg, "check");
        if (!msg) {
          accountApi
            .checkPhoneUsed({
              params: {
                phone: this.editAccountData.phone
              }
            })
            .then(res => {
              if (res.code === 0) {
                this.checkPhoneRes = res.data;
              }
            });
        } else {
          this.checkPhoneRes = {};
        }
      });
    },
    // 点击右上角的×关闭时，只清空队列，不调用新增
    uploadDialogClose() {
      this.uploadQuene = [];
      this.$refs.uploadFile.clearFiles();
      this.uploadQueneDialogVisible = false;
    },
    // 上传文件
    uploadFile(file) {
      var client = new OSS({
        region: "oss-cn-hangzhou",
        accessKeyId: this.util.decrypt(process.env.AES_OSS_ID),
        accessKeySecret: this.util.decrypt(process.env.AES_OSS_SECRET),
        bucket: process.env.bucket
      });
      let address =
        "smartConstructSiteInvestmentSituation/acceptanceReport/" +
        moment().format("YYYY-MM-DD HH:mm:ss") +
        file.file.name;
      client
        .multipartUpload(address, file.file, {
          progress: percent => {
            // this.$set(this.uploadQuene[this.uploadFileIndex], 'percent', parseInt(percent * 100) + '%')
            this.uploadQuene[this.uploadFileIndex].percent =
              parseInt(percent * 100) + "%";
            console.log(percent, "percent");
          }
        })
        .then(res => {
          // data.attach = 'http://dev-consult-new.oss-cn-hangzhou.aliyuncs.com/' + res.name
          this.uploadQuene[this.uploadFileIndex].status = "resolve";
          this.uploadQuene[
            this.uploadFileIndex
          ].file_address = res.res.requestUrls[0].split("?")[0];
          this.uploadQuene[
            this.uploadFileIndex
          ].fileAddress = res.res.requestUrls[0].split("?")[0];
          this.uploadFileIndex++;
          this.uploadFileQuene();
          console.log(res, this.uploadQuene, "111");
        });
    },
    async closeDialog() {
      // await this.createAcceptposition();
      this.getFiles(this.uploadQuene);
      this.$refs.uploadFile.clearFiles();
      this.uploadQueneDialogVisible = false;
    },
    // async createAcceptposition() {
    //   const data = await ZHGDConsSitApi.uploadFiles({
    //     data: {
    //       associationId: "0",
    //       files:
    //     }
    //   });
    //   let code = data.code;
    //   if (code === 0) {
    //     this.queryFiles();
    //     this.$message.success("操作成功");
    //   }
    // },
    // async queryFiles() {
    //   // 查询部位
    //   const data = await ZHGDConsSitApi.queryFiles({
    //     params: {
    //       projectId: this.$route.query.project_id
    //     }
    //   });
    //   let code = data.code;
    //   if (code === 0) {
    //     this.filesList = data.data;
    //   }
    // },
    getFiles(arr) {
      if (arr.length > 0) {
        arr.forEach(ele => {
          this.filesList.push({
            fileAddress: ele.fileAddress,
            fileName: ele.fileName
          });
        });
      }
      console.log(this.filesList, "this.filesList");
      // return list;
    },
    //子组件返回的值
    chooseOrgCb(data) {
      console.log("岗位数据data=", data);
      this.editAccountData.job_id = data.id;
      // this.getJobList();
      console.log(
        "9999-this.jobList=",
        this.jobList,
        "editAccountData.job_id=",
        this.editAccountData.job_id,
        "data=",
        data
      );

      // if (data.length != 0) {
      //   this.approverArr = data;
      //   data.forEach(ele => {
      //     this.formMaterialASlert.businessRecipient = this.formMaterialASlert.businessRecipient + ele.user_name + ' ';
      //   })
      // }
    },
    // 打开选择项目弹窗
    openManageDialog() {
      //this.organizationDialogVisible = true
      this.chooseOrgDialogVisible = true;
    },
    dialogClose() {
      this.checkPhoneRes = {};
      this.$refs.editAccountData.resetFields();
      this.$emit("update:dialogVisible", false);
    },
    // 保存按钮
    saveData(editAccountData) {
      this.$refs[editAccountData].validate(valid => {
        if (valid) {
          console.log(this.filesList, "filesList55555");
          if (this.dialogStatus === "add") {
            accountApi
              .addAccount({
                data: {
                  user_no: this.editAccountData.user_name,
                  user_name: this.editAccountData.real_name,
                  phone: this.editAccountData.phone,
                  job_id: this.editAccountData.job_id,
                  job_cert: this.filesList
                }
              })
              .then(res => {
                if (res.code === 0) {
                  this.dialogClose();
                  this.$message.success("添加成功");
                  this.$emit("refreshData", editAccountData);
                }
              });
          } else {
            accountApi
              .editAccount({
                data: {
                  user_id: this.editAccountData.user_id,
                  user_no: this.editAccountData.user_name,
                  user_name: this.editAccountData.real_name,
                  phone: this.editAccountData.phone,
                  job_id: this.editAccountData.job_id,
                  job_cert: this.filesList
                }
              })
              .then(res => {
                if (res.code === 0) {
                  this.dialogClose();
                  this.$message.success("修改成功");
                  this.$emit("refreshData", editAccountData);
                }
              });
          }
          // this.dialogClose()
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 取消按钮
    cancelData(editAccountData) {
      this.dialogClose();
      this.$refs[editAccountData].resetFields();
    },
    // 获取岗位列表数据
    getJobList() {
      accountApi
        .getJob({
          data: {}
        })
        .then(res => {
          this.jobList = [];
          this.jobList = res.data;
        });
    },
    handleFileSuccess() {},
    beforeFileUpload(file) {},
    // 文件超出数量限制钩子函数
    handleFileExceed(file, filelist) {
      let count = file.length + this.filesList.length;
      if (count > 5) {
        this.$message.warning("最多同时上传5个文件");
      }
    },
    // 通过队列的方式上传
    uploadFileQuene() {
      if (this.uploadFileIndex < this.uploadQuene.length) {
        this.uploadQuene[this.uploadFileIndex].status = "ready";
        this.$refs.uploadFile.submit();
      }
    },
    handleFileChange(file, filelist) {
      // 简易版debounce，以最后一次为准
      clearTimeout(this.timerId);
      this.timerId = setTimeout(() => {
        // elementui 上传组件会把filelist中所有status为ready的数据上传，
        // 因此首先把所有数据的status置为waiting，然后依次把status置为ready，实现队列效果
        filelist.map(item => {
          item.file_alias = item.name;
          item.fileName = item.name;
          item.file_ext = item.name.split(".")[1];
          item.file_size = (item.size / (1024 * 1024)).toFixed(2) + "M";
          item.status = "waiting";
          this.$set(item, "percent", "0%");
        });
        this.uploadQuene = filelist;
        this.uploadFileIndex = 0;
        this.uploadQueneDialogVisible = true;
        // 控制文件一个个上传
        this.uploadFileQuene();
      }, 300);
    },
    deleteCurrentRow(item, ind) {
      this.$confirm(`确定要删除"${item.fileName}"？`, {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          if (ind !== -1) {
            this.filesList.splice(ind, 1);
          }
          this.$message.success("删除成功");
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    getCurrentDocType(fileAddrPath) {
      //当前文件类型
      let result = fileAddrPath.substring(fileAddrPath.length - 3);
      return result;
    },
    async lookAndDown(item) {
      if ((await this.getCurrentDocType(item.fileAddress)) === "pdf") {
        window.open(item.fileAddress, "_blank");
      } else if ((await this.getCurrentDocType(item.fileAddress)) === "jpg") {
        let alink = document.createElement("a");
        alink.href =
          item.fileAddress + "?response-content-type=application/octet-stream";
        alink.download = item.fileName; // 图片名
        alink.click();
      } else {
        window.open(
          "https://view.officeapps.live.com/op/view.aspx?src=" +
            item.fileAddress,
          "_blank"
        );
      }
    }
  },
  watch: {
    dialogVisible(newval, oldval) {
      this.visible = newval;
    },
    dialogForm: {
      handler(newval, oldval) {
        this.editAccountData = JSON.parse(JSON.stringify(newval));
        console.log(this.editAccountData, " this.editAccountData88888");
        this.filesList =
          this.dialogStatus === "add" ? [] : this.editAccountData.job_cert;
        this.getJobList(); //岗位列表数据
        //获取id
        this.jobList.forEach(ele => {
          if (ele.job_name == this.editAccountData.job_id) {
            this.editAccountData.job_id = ele.job_id;
          }
        });
        console.log(
          newval,
          JSON.stringify(newval),
          this.editAccountData,
          "watch"
        );
      },
      deep: true
    },
    dialogStatus(newval, oldval) {},
    dialogId(newval, oldval) {
      //this.edit_user_id = newval
    }
  },
  created() {
    this.getJobList();
  },
  mounted() {}
};
</script>
<style scoped lang='scss'>
.edit-account-dialog-container {
  .select-class {
    display: none;
  }

  .phone-row {
    margin-bottom: 40px;
  }

  .phone {
    width: calc(100% - 75px);
  }

  .check-phone-res {
    position: absolute;
    width: 340px;
    margin-left: 100px;
    bottom: -20px;
    height: 40px;

    &.alert {
      color: red;
    }

    &.normal {
      color: #4fc669;
    }
  }

  .tips {
    color: red;
    position: absolute;
    left: 63%;
    bottom: 30px;
  }

  .dialog-footer {
    text-align: center;
  }

  .edit-account-form {
    .el-select {
      width: 100%;
    }
  }
  .upload-quene-list {
    .upload-quene-item {
      width: 100%;
      height: 48px;
      border-bottom: 1px solid #e5e5e5;
      display: flex;
      align-items: center;
      justify-content: flex-start;
      padding-left: 40px;
      font-size: 14px;
      color: #666;

      &:first-child {
        border-top: 1px solid #e5e5e5;
      }

      .file-name {
        width: 350px;
        margin-right: 80px;
        display: flex;
        align-items: center;
        img {
          width: 24px;
          height: 24px;
          margin-right: 15px;
        }
      }

      .file-size {
        width: 60px;
        margin-right: 40px;
      }

      .dir-name {
        width: 100px;
        margin-right: 40px;
        color: #1890ff;
      }

      .status {
        color: #333;
        display: flex;
        align-items: center;

        i {
          color: #52c41a;
          margin-right: 8px;
        }
      }
    }
  }
}
.accept-position {
  margin-top: 15px;
  ul {
    li {
      color: #409eff;
      height: 30px;
      line-height: 30px;
      display: flex;
      flex-direction: row;
      margin-bottom: 12px;
      p:nth-child(1) {
        width: 60%;
        white-space: nowrap; /* 防止换行 */
        overflow: hidden; /* 隐藏超出范围的内容 */
        text-overflow: ellipsis; /* 显示省略号 */
      }
      p:nth-last-child(1) {
        width: 40%;
        display: flex;
        flex-direction: row;
        justify-content: flex-end;
      }
    }
    li:nth-last-child(1) {
      margin-bottom: 0px !important;
    }
  }
}
</style>